package com.qupai.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qupai.constant.MessageConstant;
import com.qupai.context.BaseContext;
import com.qupai.dto.UserDTO;
import com.qupai.dto.UserLoginDTO;
import com.qupai.entity.User;
import com.qupai.exception.LoginFailedException;
import com.qupai.mapper.UserMapper;
import com.qupai.properties.WeChatProperties;
import com.qupai.service.UserService;
import com.qupai.utils.HttpClientUtil;
import com.qupai.vo.UserVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    //微信接口服务地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private UserMapper userMapper;

    /**
     * 微信登录
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前微信用户的openid
        String openid = getOpenid(userLoginDTO.getCode());
        System.out.println("当前微信用户的openid: "+openid);

        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }


        //判断当前用户是否为新用户
//        User user = userMapper.getByOpenid(openid);
        QueryWrapper<User>wrapper=new QueryWrapper<>();
        wrapper.lambda()
                .eq(User::getOpenid,openid);
        User user = userMapper.selectOne(wrapper);

        BigDecimal balance = BigDecimal.valueOf(0);

        //如果为新用户，自动完成注册
        if (user==null){
            log.info("注册新用户");
            user=User.builder()
                    .openid(openid)
                    .name("广大人")
                    .sex("0")
                    .collegesId(20L)
                    .phone("136xxxxxxxx")
                    .studentId("322061000xx")
                    .major(2L)
                    .className("计科221")
                    .avatar("https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0")
                    .walletCommon(balance)
                    .walletVolunteer(balance)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        //返回这个用户的对象

        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     */
    private String getOpenid(String code){
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        System.out.println(map);
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }

    /**
     * 修改用户信息
     */
    @Override
    public void update(UserDTO userDTO) {
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        userMapper.updateById(user);
    }

    /**
     * 查询用户信息回显
     */
    @Override
    public UserVO userlist() {
        Long userId = BaseContext.getCurrentId();
        UserVO userVO=new UserVO();
        User user = userMapper.selectById(userId);
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
}
